import Router from "vue-router";
import EventBus from "@/modules/eventBus";
import {routerMetaPlain} from "./routerMeta";
import {assembleTreeFromArray, messageHandle} from "@/utils";
import {clearStorage, getStorage, StorageKey} from "@/config/sessions";
import store from "../store";

export const routes = assembleTreeFromArray({
  srcData: routerMetaPlain(),
  parentKey: 'parent',
  childKey: 'name'
});

export const router = new Router({
  mode: "history",
  scrollBehavior() {
    return {x: 0, y: 0};
  },
  routes: [
    ...routes,
    {path: '*', component: () => import('../page/NotFound')}
  ]
});

// todo 防止路由跳到本页面传的参数一样的情况下控制台报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const originalReplace = Router.prototype.replace;
Router.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch((err) => err);
};

router.beforeEach((to, from, next) => {
  store.dispatch('clearCancel');
  next();
  const {meta = {}} = to;
  const {ignoreToken} = meta;
  const token = getStorage(StorageKey.token);
  // 不需要校验token
  if (ignoreToken) {
    next();
  } else {
    if (token) {
      const role = localStorage.getItem('role')
      if (role === 'guest' && to.meta.isGuest) {
        next() // 允许访问
      } else if (role === 'admin' || role === 'user') {
        next();
      } else {
        next('/admin/IDE/project')
      }
    } else {
      messageHandle({type: 'warning', msg: '请重新登录'});
      EventBus.$emit('tokenExpired', true);
      clearStorage();
      next();
    }
  }
});
